﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;

namespace LocalizerControl
{
    using UDPListener;

    public partial class Form1 : Form
    {
        #region Member Variables
        private Boolean running;
        
        private IPEndPoint remoteEndPoint;
        private UdpClient udpBroadcaster;
        private UDPListener listener;
        private int groupPort;

        private long start;
        private long stop;

        #endregion

        #region Constructor
        public Form1()
        {
            InitializeComponent();

            rxSetter1.DefaultIPAddress = "10.0.0.110";
            rxSetter1.RXNumber = 1;

            rxSetter2.DefaultIPAddress = "10.0.0.111";
            rxSetter2.RXNumber = 2;

            rxSetter3.DefaultIPAddress = "10.0.0.112";
            rxSetter3.RXNumber = 3;

            rxSetter4.DefaultIPAddress = "10.0.0.113";
            rxSetter4.RXNumber = 4;

            running = false;

            groupPort = 2000;

            remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
            udpBroadcaster = new UdpClient();
            udpBroadcaster.ExclusiveAddressUse = false;
            udpBroadcaster.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udpBroadcaster.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
            udpBroadcaster.Client.Bind(remoteEndPoint);

            listener = new UDPListener(groupPort);
            listener.MessageReceived += new UDPEventHandler(UDP_MessageReceived);

        }
        #endregion

        #region Events
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox2.Lines = new String[]{""};
            button1.BackColor = Color.Green;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (running)
            {
                e.Cancel = true;
                MessageBox.Show("You cannot exit the program if the localization system is running!!!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (running)
            {
                button1.Text = "Go";
                button1.BackColor = Color.Green;
                running = false;
                timer1.Stop();
                listener.Stop();
            }
            else
            {
                button1.Text = "Stop";
                button1.BackColor = Color.Red;
                running = true;
                timer1.Start();
                listener.Start();
            }

            Stopwatch stopWatch = new Stopwatch();
         
            long start = Stopwatch.GetTimestamp();
            stopWatch.Start();

            stopWatch.Stop();
            long stop = Stopwatch.GetTimestamp();

            TimeSpan ts = stopWatch.Elapsed;
            String elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);

            long frequency = Stopwatch.Frequency;
            Console.WriteLine("  Timer frequency in ticks per second = {0}",
                frequency);
            
            long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
            Console.WriteLine("  Timer is accurate within {0} nanoseconds",
                nanosecPerTick);

            //Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);

            textBox1.Text=elapsedTime;
            System.Console.WriteLine("Result: " + ts.Ticks );

            System.Console.WriteLine("Ticks: " + (double)(stop - start)/(double)frequency);   
        }

    
        private void UDP_MessageReceived(object sender, UDPEventArgs e)
        {
            String msg = e.Message.Trim();
            String sndr = e.Sender.Trim();
            long stopTime = e.TimeStamp;
            long frequency = Stopwatch.Frequency;
            if (sndr == "10.0.0.100")
            {
                Console.WriteLine("Sprucegoose sez:");
                Console.WriteLine(msg);
                Console.WriteLine("Elapsed time: {0}", (stopTime - start)/(double)frequency);
            }
            //    textBox2.AppendText(msg);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Byte[] strBytes = Encoding.ASCII.GetBytes("<P>\r\n");
            udpBroadcaster.Send(strBytes, strBytes.Length, new IPEndPoint(IPAddress.Parse("10.0.0.255"), groupPort));
            start = Stopwatch.GetTimestamp();
        }
        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            Byte[] strBytes = Encoding.ASCII.GetBytes("<G>\r\n");
            udpBroadcaster.Send(strBytes, strBytes.Length, new IPEndPoint(IPAddress.Parse("10.0.0.100"), groupPort));
            start = Stopwatch.GetTimestamp();
        }

        private void messageWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            
            long cycleCount = 0;

            while (!e.Cancel)
            {
                if(cycleCount % 10 == 0)


                System.Threading.Thread.Sleep(10);
                cycleCount++;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            saveFileDialog1.ShowDialog();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space && running)
            {
                running = false;
                MessageBox.Show("Flight Aborted!", "Abort.", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                button1.BackColor = Color.Green;
                button1.Text = "Go";
            }
        }

       

    }
}
